package com.nets.encoder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.nets.packet.PacketI;
import com.nets.pool.ServerPool;
import com.nets.util.LogUtil;
import com.nets.util.ZipUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.CharsetUtil;

/**
 * @author sig
 * @since 2016/9/17
 */
public class PacketEncoder extends MessageToByteEncoder<PacketI> {

    @Override
    protected void encode(ChannelHandlerContext ctx,
                          PacketI packet,
                          ByteBuf out) throws Exception {
        if (0 == packet.getType()) return;
        String jsonString = JSON.toJSONString(packet.getObject(),
                SerializerFeature.DisableCircularReferenceDetect);
        byte[] data = jsonString.getBytes(CharsetUtil.UTF_8);

        if (null != LogUtil.console && ServerPool.logSwitch)
            LogUtil.console.info("The server response type:" +
                    packet.getType() + "|packet:" + jsonString);
        boolean isZip = isZip(data);

        if (isZip) data = ZipUtil.gZip(data);
        out.writeByte(-11); // 帧头
        out.writeByte(isZip ? 1 : 0);
        out.writeInt(data.length);
        out.writeInt(packet.getType());
        out.writeBytes(data);
        out.writeByte(-99); // 帧尾
        out.retain();
        out.release();
    }

    private boolean isZip(byte[] data) {
        return 512 < data.length;
    }
}
